/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.constant.SecurityConstants;
import org.springblade.common.tool.AuthUtils;
import org.springblade.gateway.props.AuthProperties;
import org.springblade.gateway.provider.AuthProvider;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 验证码
 *
 * @author Chill
 */
@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
	private AuthProperties authProperties;
	private ObjectMapper objectMapper;
	private final RedisTemplate redisTemplate;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		String path = exchange.getRequest().getURI().getPath();
		ServerHttpRequest request = exchange.getRequest();

		// 不是登录请求，直接向下执行
		if (StrUtil.containsAnyIgnoreCase(path
			, SecurityConstants.OAUTH_TOKEN_URL)) {
			// 刷新token，直接向下执行
			String grantType = request.getQueryParams().getFirst("grantType");
			String tenantId = request.getQueryParams().getFirst("tenantId");
			if (!StrUtil.equals(SecurityConstants.PASSWORD, grantType) || !StrUtil.equals("000000",tenantId)) {
				return chain.filter(exchange);
			}
			try {
				//校验验证码
				checkCode(exchange.getRequest());
			} catch (Exception e) {
				ServerHttpResponse response = exchange.getResponse();
				response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
				try {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("code",400);
					jsonObject.put("msg",e.getMessage());
					return response.writeWith(Mono.just(response.bufferFactory()
						.wrap(objectMapper.writeValueAsBytes(
							jsonObject))));
				} catch (JsonProcessingException e1) {
					log.error("对象输出异常", e1);
				}
			}
			return chain.filter(exchange);
		}
		return chain.filter(exchange);
	}
	/**
	 * 检查code
	 *
	 * @param request
	 */
	@SneakyThrows
	private void checkCode(ServerHttpRequest request) {
		String code = request.getHeaders().getFirst(AuthUtils.CAPTCHA_HEADER_CODE);
		String key = request.getHeaders().getFirst(AuthUtils.CAPTCHA_HEADER_KEY);
		// 获取验证码
		String redisCode = String.valueOf(redisTemplate.opsForValue().get(CacheNames.CAPTCHA_KEY + key));

		// 判断验证码
		if (code == null || !StrUtil.equalsIgnoreCase(redisCode, code)) {
			redisTemplate.delete(key);
			throw new RuntimeException(AuthUtils.CAPTCHA_NOT_CORRECT);
		}
		redisTemplate.delete(key);
	}

	@Override
	public int getOrder() {
		return -100;
	}

}
